<template>
  <div class="base-card">
    <el-card :shadow="cardShadow">
      <template #header>
        <slot name="card-header"></slot>
      </template>
      <el-form
        :model="formData"
        :rules="formRules"
        label-width="auto"
        class="login-form"
        ref="loginFormEl"
      >
        <slot name="form-items"></slot>
      </el-form>
      <slot name="form-extra"></slot>
      <template #footer>
        <section class="card-footer">
          <div class="login-btn">
            <el-button type="primary" plain class="login-btn" @click="handleSubmit">
              {{ leftBtnText }}
            </el-button>
            <el-button class="reset-btn" @click="resetForm">清空</el-button>
          </div>
          <div class="tips" v-if="tiplinkText">
            <el-link :disabled="disableTipLink" @click="handleTipClick">
              {{ tiplinkText }}
            </el-link>
          </div>
        </section>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import { useTemplateRef } from 'vue'
import { ElMessageBox } from 'element-plus'

const formData = defineModel('formData')
const { formRules, leftBtnText, disableTipLink, tiplinkText } = defineProps({
  formRules: { type: Object, default: () => ({}) },
  leftBtnText: { type: String, default: '提交' },
  disableTipLink: { type: Boolean, default: false },
  tiplinkText: { type: String, default: '' },
  cardShadow: { type: String, default: 'always' },
})
const emit = defineEmits(['submit', 'tipClick'])

const loginFormEl = useTemplateRef('loginFormEl')

const handleSubmit = async () => {
  if (!loginFormEl.value) return
  await loginFormEl.value.validate((valid) => {
    if (valid) {
      emit('submit')
    } else {
      ElMessageBox.alert(`表单验证失败，请检查输入信息`, {
        confirmButtonText: '确定',
        type: 'error',
      })
    }
  })
}
const resetForm = () => {
  if (!loginFormEl.value) return
  loginFormEl.value.resetFields()
}
const handleTipClick = () => {
  emit('tipClick')
}

defineExpose({
  resetForm, //暴露resetForm方法
})
</script>

<style lang="scss" scoped>
.base-card {
  :deep(.el-card) {
    .el-card__header {
      padding-top: 1.5rem;
      padding-bottom: 0;
      border-bottom: none;
    }
    .el-card__body {
      padding-top: 1.5rem;
      padding-bottom: 0.7rem;
      .el-form {
        .el-form-item {
          margin-bottom: 1.5rem;
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
    .el-card__footer {
      padding-top: 0;
      padding-bottom: 1.5rem;
      border-top: none;
      .card-footer {
        text-align: center;
        .tips {
          margin-top: 0.7rem;
          .el-link {
            display: block;
            width: max-content;
            margin: 0 auto;
            a {
              text-decoration: none;
              color: inherit;
              cursor: inherit;
            }
          }
        }
      }
    }
  }
}
</style>
